{
 "cells": [
  {
   "cell_type": "markdown",
   "id": "a8b892c8",
   "metadata": {},
   "source": [
    "Printed and electronic copies of *Modeling and Simulation in Python* are available from [No Starch Press](https://nostarch.com/modeling-and-simulation-python) and [Bookshop.org](https://bookshop.org/p/books/modeling-and-simulation-in-python-allen-b-downey/17836697?ean=9781718502161) and [Amazon](https://amzn.to/3y9UxNb)."
   ]
  },
  {
   "cell_type": "markdown",
   "id": "affecting-malta",
   "metadata": {},
   "source": [
    "# Modeling"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "pressed-palestinian",
   "metadata": {
    "tags": []
   },
   "source": [
    "*Modeling and Simulation in Python*\n",
    "\n",
    "Copyright 2021 Allen Downey\n",
    "\n",
    "License: [Creative Commons Attribution-NonCommercial-ShareAlike 4.0 International](https://creativecommons.org/licenses/by-nc-sa/4.0/)"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "confirmed-budapest",
   "metadata": {
    "tags": []
   },
   "source": [
    "## Jupyter\n",
    "\n",
    "Welcome to *Modeling and Simulation in Python*, and welcome to Jupyter.\n",
    "\n",
    "This is a Jupyter notebook, which is a development environment where you can write and run Python code.  Each notebook is divided into cells.  Each cell contains either text (like this cell) or Python code."
   ]
  },
  {
   "cell_type": "markdown",
   "id": "danish-scope",
   "metadata": {
    "tags": []
   },
   "source": [
    "To run a cell, hold down SHIFT and press ENTER.  \n",
    "\n",
    "* If you run a text cell, Jupyter formats the text and displays the result.\n",
    "\n",
    "* If you run a code cell, Jupyter runs the Python code in the cell and displays the result, if any.\n",
    "\n",
    "The following cells check whether the libraries we need are installed.  If so, the cells produce no output.  If not, you'll see updates from the installer."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 1,
   "id": "passive-dayton",
   "metadata": {
    "tags": []
   },
   "outputs": [],
   "source": [
    "# install Pint if necessary\n",
    "\n",
    "try:\n",
    "    from pint import UnitRegistry\n",
    "except ImportError:\n",
    "    !pip install pint"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "id": "prompt-committee",
   "metadata": {
    "tags": []
   },
   "outputs": [],
   "source": [
    "# download modsim.py if necessary\n",
    "\n",
    "from os.path import basename, exists\n",
    "\n",
    "def download(url):\n",
    "    filename = basename(url)\n",
    "    if not exists(filename):\n",
    "        from urllib.request import urlretrieve\n",
    "        local, _ = urlretrieve(url, filename)\n",
    "        print('Downloaded ' + local)\n",
    "    \n",
    "download('https://github.com/AllenDowney/ModSimPy/raw/master/' +\n",
    "         'modsim.py')"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 3,
   "id": "fifteen-train",
   "metadata": {
    "tags": []
   },
   "outputs": [],
   "source": [
    "# import functions from modsim\n",
    "\n",
    "from modsim import *"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "chronic-moore",
   "metadata": {},
   "source": [
    "This chapter introduces the modeling framework we will use throughout the book, and works through our first example, using a simple model of physics to evaluate the claim that a penny falling from the height of the Empire State Building could kill someone if it hit them on the head. Also, you'll see how to do computation in Python with units like meters and seconds."
   ]
  },
  {
   "cell_type": "markdown",
   "id": "extensive-proposition",
   "metadata": {},
   "source": [
    "This chapter is available as a Jupyter notebook where you can read the text, run the code, and work on the exercises. \n",
    "Click here to access the notebooks: <https://allendowney.github.io/ModSimPy/>."
   ]
  },
  {
   "cell_type": "markdown",
   "id": "hourly-financing",
   "metadata": {},
   "source": [
    "## The Modeling Framework\n",
    "\n",
    "This book is about modeling and simulating physical systems. The\n",
    "following diagram shows what I mean by *modeling*:\n",
    "\n",
    "![Diagram of the modeling framework.](https://github.com/AllenDowney/ModSim/raw/main/figs/modeling_framework.png)"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "structured-receiver",
   "metadata": {},
   "source": [
    "Starting in the lower left, the *system* is something in the real\n",
    "world we are interested in. \n",
    "To model the system, we have to decide which elements of the real world to include and which we can leave out.\n",
    "This process is called *abstraction*.\n",
    "\n",
    "The result of abstraction is a *model*, which is a description of the system that includes only the features we think are essential. A model\n",
    "can be represented in the form of diagrams and equations, which can be\n",
    "used for mathematical *analysis*. It can also be implemented in the\n",
    "form of a computer program, which can run *simulations*.\n",
    "\n",
    "The result of analysis and simulation might be a *prediction* about\n",
    "what the system will do, an *explanation* of why it behaves the way it\n",
    "does, or a *design* intended to achieve a purpose.\n",
    "\n",
    "We can *validate* predictions and test designs by taking\n",
    "*measurements* from the real world and comparing the *data* we get\n",
    "with the results from analysis and simulation."
   ]
  },
  {
   "cell_type": "markdown",
   "id": "center-accommodation",
   "metadata": {},
   "source": [
    "For any physical system, there are many possible models, each one\n",
    "including and excluding different features, or including different\n",
    "levels of detail. The goal of the modeling process is to find the model\n",
    "best suited to its purpose (prediction, explanation, or design).\n",
    "\n",
    "Sometimes the best model is the most detailed. If we include more\n",
    "features, the model is more realistic, and we expect its predictions to\n",
    "be more accurate.\n",
    "But often a simpler model is better. If we include only the essential\n",
    "features and leave out the rest, we get models that are easier to work\n",
    "with, and the explanations they provide can be clearer and more\n",
    "compelling."
   ]
  },
  {
   "cell_type": "markdown",
   "id": "confirmed-highlight",
   "metadata": {},
   "source": [
    "As an example, suppose someone asks you why the orbit of the Earth is\n",
    "elliptical. If you model the Earth and Sun as point masses (ignoring\n",
    "their actual size), compute the gravitational force between them using\n",
    "Newton's law of universal gravitation, and compute the resulting orbit\n",
    "using Newton's laws of motion, you can show that the result is an\n",
    "ellipse.\n",
    "Of course, the actual orbit of Earth is not a perfect ellipse, because\n",
    "of the gravitational forces of the Moon, Jupiter, and other objects in\n",
    "the solar system, and because Newton's laws of motion are only\n",
    "approximately true (they don't take into account relativistic effects).\n",
    "But adding these features to the model would not improve the\n",
    "explanation; more detail would only be a distraction from the\n",
    "fundamental cause. However, if the goal is to predict the position of\n",
    "the Earth with great precision, including more details might be\n",
    "necessary."
   ]
  },
  {
   "cell_type": "markdown",
   "id": "stretch-geneva",
   "metadata": {},
   "source": [
    "Choosing the best model depends on what the model is for. It is usually\n",
    "a good idea to start with a simple model, even if it is likely to be too\n",
    "simple, and test whether it is good enough for its purpose. Then you can\n",
    "add features gradually, starting with the ones you expect to be most\n",
    "essential. This process is called *iterative modeling*.\n",
    "\n",
    "Comparing results of successive models provides a form of *internal\n",
    "validation*, so you can catch conceptual, mathematical, and software\n",
    "errors. And by adding and removing features, you can tell which ones\n",
    "have the biggest effect on the results, and which can be ignored.\n",
    "\n",
    "Comparing results to data from the real world provides *external\n",
    "validation*, which is generally the strongest test.\n",
    "\n",
    "The modeling framework is pretty abstract; the following example might make it clearer."
   ]
  },
  {
   "cell_type": "markdown",
   "id": "criminal-lunch",
   "metadata": {},
   "source": [
    "## The Falling Penny Myth\n",
    "\n",
    "You might have heard that a\n",
    "penny dropped from the top of the Empire State Building would be going\n",
    "so fast when it hit the pavement that it would be embedded in the\n",
    "concrete; or if it hit a person, it would break their skull.\n",
    "\n",
    "We can test this myth by making and analyzing two models. For the first model,\n",
    "we'll assume that the effect of air resistance is small. In that case, the primary force acting on the penny is gravity, which causes the penny to accelerate downward.\n",
    "\n",
    "If the initial velocity is 0 and the acceleration, $a$, is constant, the velocity after $t$ seconds is \n",
    "\n",
    "$$v = a t$$\n",
    "\n",
    "and the distance the penny has dropped is \n",
    "\n",
    "$$x = a t^2 / 2$$ \n",
    "\n",
    "To find the time until the penny reaches the sidewalk, we can solve for $t$:\n",
    "\n",
    "$$t = \\sqrt{ 2 x / a}$$ \n",
    "\n",
    "Plugging in the acceleration of gravity, $a = 9.8$ m/s$^2$, and the height of the Empire State Building, $x = 381$ m, we get $t = 8.8$ s. \n",
    "\n",
    "Then computing $v = a t$ we get a velocity on impact of $86$ m/s, which is about 190 miles per hour. That sounds like it could hurt."
   ]
  },
  {
   "cell_type": "markdown",
   "id": "documentary-diagnosis",
   "metadata": {},
   "source": [
    "Of course, these results are not exact because the model is based on simplifications. For example, we assume that gravity is constant. \n",
    "In fact, the force of gravity is different on different parts of the globe, and it gets weaker as you move away from the surface. \n",
    "But these differences are small, so ignoring them is probably a good choice for this problem.\n",
    "\n",
    "On the other hand, ignoring air resistance is not a good choice, because in this scenario its effect is substantial.\n",
    "Once the penny gets to about 29 m/s, the upward force of air resistance equals the downward force of gravity, so the penny stops accelerating.\n",
    "This is the *terminal velocity* of the penny in air.\n",
    "\n",
    "And that suggests a second model, where the penny accelerates until it reaches terminal velocity; after that, acceleration is 0 and velocity is constant.\n",
    "In this model, the penny hits the sidewalk at about 29 m/s.\n",
    "That's much less than 86 m/s, which is what the first model predicts.\n",
    "Getting hit with a penny at that speed might hurt, but it would be unlikely to cause real harm. And it would not damage concrete."
   ]
  },
  {
   "cell_type": "markdown",
   "id": "recent-appliance",
   "metadata": {},
   "source": [
    "The statistician George Box famously said \"All models are wrong, but\n",
    "some are useful.\" He was talking about statistical models, but his wise words apply to all kinds of models. Our first model, which ignores air resistance, is very wrong, and probably not useful. The second model, which takes air resistance into account, is still wrong, but it's better, and it's good enough to refute the myth.\n",
    "\n",
    "The television show *Mythbusters* has tested the myth of the falling\n",
    "penny more carefully; you can view the results at\n",
    "<https://modsimpy.com/myth/>. Their work is based on a mathematical model of motion, measurements to determine the force of air resistance on a penny, and a physical model of a human head."
   ]
  },
  {
   "cell_type": "markdown",
   "id": "brief-zoning",
   "metadata": {},
   "source": [
    "## Computation In Python\n",
    "\n",
    "Let me show you how I computed the results from the\n",
    "previous section using Python.\n",
    "First we'll create a variable to represent acceleration due to gravity in meters per second squared (m/s$^2$)."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 4,
   "id": "eleven-marine",
   "metadata": {},
   "outputs": [],
   "source": [
    "a = 9.8"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "upset-myanmar",
   "metadata": {},
   "source": [
    "A *variable* is a name that corresponds to a value. In this example, the name is `a` and the value is the number `9.8`.\n",
    "\n",
    "Suppose we let the penny drop for $3.4$ seconds (s).  I'll create a variable to represent this time:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 5,
   "id": "following-launch",
   "metadata": {},
   "outputs": [],
   "source": [
    "t = 3.4"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "greek-heritage",
   "metadata": {},
   "source": [
    "Now we can compute the velocity of the penny after `t` seconds."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 6,
   "id": "mature-duration",
   "metadata": {},
   "outputs": [],
   "source": [
    "v = a * t"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "serial-pilot",
   "metadata": {},
   "source": [
    "Python uses the symbol `*` for multiplication.  The other arithmetic operators are `+` for addition, `-` for subtraction, `/` for division, and `**` for exponentiation."
   ]
  },
  {
   "cell_type": "markdown",
   "id": "qualified-diabetes",
   "metadata": {},
   "source": [
    "After you assign a value to a variable, you can display the value like this:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 7,
   "id": "considered-inclusion",
   "metadata": {},
   "outputs": [],
   "source": [
    "v"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "northern-saturday",
   "metadata": {},
   "source": [
    "After $3.4$ s, the velocity of the penny is about $33$ m/s (ignoring air resistance).  Now let's see how far it would travel during that time:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 8,
   "id": "valued-electricity",
   "metadata": {},
   "outputs": [],
   "source": [
    "x = a * t**2 / 2\n",
    "x"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "yellow-business",
   "metadata": {},
   "source": [
    "It would travel about $56$ m.  Now, going in the other direction, let's compute the time it takes to fall 381 m, the height of the Empire State Building."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 9,
   "id": "closed-month",
   "metadata": {},
   "outputs": [],
   "source": [
    "h = 381"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "fuzzy-lease",
   "metadata": {},
   "source": [
    "For this computation, we need the square root function, `sqrt`, which is provided by a library called NumPy.\n",
    "Before we can use it, we have to import it like this:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 10,
   "id": "nuclear-clone",
   "metadata": {},
   "outputs": [],
   "source": [
    "from numpy import sqrt"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "unlimited-swiss",
   "metadata": {},
   "source": [
    "Now we can use it like this:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 11,
   "id": "quarterly-nightmare",
   "metadata": {},
   "outputs": [],
   "source": [
    "t = sqrt(2 * h / a)\n",
    "t"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "velvet-oklahoma",
   "metadata": {},
   "source": [
    "With no air resistance, it would take about $8.8$ s for the penny to reach the sidewalk."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 12,
   "id": "quality-external",
   "metadata": {},
   "outputs": [],
   "source": [
    "v = a * t\n",
    "v"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "active-lobby",
   "metadata": {},
   "source": [
    "And its velocity on impact would be about $86$ m/s."
   ]
  },
  {
   "cell_type": "markdown",
   "id": "human-phase",
   "metadata": {},
   "source": [
    "### False Precision\n",
    "\n",
    "Python displays results with about 16 digits, which gives the impression that they are very precise, but don't be fooled.\n",
    "The numbers we get out are only as good as the numbers we put in.\n",
    "\n",
    "For example, the \"roof height\" of the Empire State Building is $380$ m (according to Wikipedia: <https://en.wikipedia.org/wiki/Empire_State_Building>).\n",
    "I chose $h=381$ m for this example on the assumption that the observation deck is on the roof and you drop the penny from a 1 meter railing.\n",
    "But that's probably not right, so we should treat this value as an approximation where only the first two digits are likely to be right.\n",
    "\n",
    "If the precision of the inputs is two digits, the precision of the outputs is two digits, *at most*.\n",
    "That's why, if the output is `86.41527642726142`, I report it as \"about 86\"."
   ]
  },
  {
   "cell_type": "markdown",
   "id": "clinical-blackjack",
   "metadata": {},
   "source": [
    "### Computation With Units\n",
    "\n",
    "The computations we just did use numbers without units.\n",
    "When we set `h=381`, we left out the meters, and when we set `a=9.8`, we left out the meters per second squared.\n",
    "And, when we got the result `v=86`, we added back the meters per second.\n",
    "\n",
    "Leaving units out of computation is a common practice, but it tends to cause errors, including the very expensive failure of the Mars Climate Orbiter in 1999 (see <https://en.wikipedia.org/wiki/Mars_Climate_Orbiter>).\n",
    "When possible, it is better to include units in the computation.\n",
    "\n",
    "To represent units, we'll use a library called Pint (<https://pint.readthedocs.io/>).\n",
    "To use it, we have to import a function called `UnitRegistry` and call it like this:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 13,
   "id": "lovely-declaration",
   "metadata": {},
   "outputs": [],
   "source": [
    "from pint import UnitRegistry\n",
    "\n",
    "units = UnitRegistry()"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "consecutive-sleeve",
   "metadata": {},
   "source": [
    "The result is an object that contains variables representing pretty much every unit you've heard of.\n",
    "For example:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 14,
   "id": "cardiac-class",
   "metadata": {},
   "outputs": [],
   "source": [
    "units.league"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 15,
   "id": "phantom-copper",
   "metadata": {},
   "outputs": [],
   "source": [
    "units.fortnight"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "unlike-opera",
   "metadata": {},
   "source": [
    "But leagues and fortnights are not part of the International System of Units\n",
    "(see <https://en.wikipedia.org/wiki/International_System_of_Units>); in the jargon, they are not \"SI units\".\n",
    "Instead, we will use `meter` and `second`."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 16,
   "id": "russian-popularity",
   "metadata": {},
   "outputs": [],
   "source": [
    "meter = units.meter\n",
    "meter"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 17,
   "id": "endless-paint",
   "metadata": {},
   "outputs": [],
   "source": [
    "second = units.second\n",
    "second"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "spiritual-scenario",
   "metadata": {
    "tags": []
   },
   "source": [
    "To find out what other units are defined, type `units.` (including the period) in the next cell.\n",
    "\n",
    "If you are on Colab, a pop-up menu should appear with a list of units.\n",
    "In other Jupyter environments, you might have to press `TAB` to get the menu."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "saving-suggestion",
   "metadata": {
    "tags": []
   },
   "outputs": [],
   "source": []
  },
  {
   "cell_type": "markdown",
   "id": "everyday-location",
   "metadata": {},
   "source": [
    "We can use `meter` and `second` to create a variable named `a` and give it the value of acceleration due to gravity. "
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 18,
   "id": "earlier-bandwidth",
   "metadata": {},
   "outputs": [],
   "source": [
    "a = 9.8 * meter / second**2\n",
    "a"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "generic-bowling",
   "metadata": {},
   "source": [
    "The result is a *quantity* with two parts, called `magnitude` and `units`, which we can access like this:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 19,
   "id": "missing-privilege",
   "metadata": {},
   "outputs": [],
   "source": [
    "a.magnitude"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 20,
   "id": "fourth-swedish",
   "metadata": {},
   "outputs": [],
   "source": [
    "a.units"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "realistic-techno",
   "metadata": {},
   "source": [
    "We can also create a quantity that represents $3.4$ s."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 21,
   "id": "apart-france",
   "metadata": {},
   "outputs": [],
   "source": [
    "t = 3.4 * second\n",
    "t"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "severe-share",
   "metadata": {},
   "source": [
    "And use it to compute the distance a penny would fall after `t` seconds with constant acceleration `a`.  "
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 22,
   "id": "alien-scout",
   "metadata": {},
   "outputs": [],
   "source": [
    "a * t**2 / 2"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "wicked-indianapolis",
   "metadata": {},
   "source": [
    "Notice that the units of the result are correct.\n",
    "If we create a quantity to represent the height of the Empire State Building:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 23,
   "id": "confidential-costs",
   "metadata": {},
   "outputs": [],
   "source": [
    "h = 381 * meter"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "hollow-programmer",
   "metadata": {},
   "source": [
    "We can use it to compute the time the penny would take to reach the sidewalk."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 24,
   "id": "studied-opera",
   "metadata": {},
   "outputs": [],
   "source": [
    "t = sqrt(2 * h / a)\n",
    "t"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "seasonal-laser",
   "metadata": {},
   "source": [
    "And the velocity of the penny on impact:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 25,
   "id": "exterior-greek",
   "metadata": {},
   "outputs": [],
   "source": [
    "v = a * t\n",
    "v"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 26,
   "id": "impaired-puzzle",
   "metadata": {
    "tags": []
   },
   "outputs": [],
   "source": [
    "assert abs(v.magnitude - 86.41527642726142) < 1e-7"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "superior-biography",
   "metadata": {},
   "source": [
    "As in the previous section, the result is about $86$, but now it has the correct units, m/s.\n",
    "\n",
    "With Pint quantities, we can convert from one set of units to another like this:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 27,
   "id": "antique-landing",
   "metadata": {},
   "outputs": [],
   "source": [
    "mile = units.mile\n",
    "hour = units.hour"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 28,
   "id": "included-failure",
   "metadata": {},
   "outputs": [],
   "source": [
    "v.to(mile/hour)"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "progressive-charleston",
   "metadata": {},
   "source": [
    "If you are more familiar with miles per hour, this result might be easier to interpret.\n",
    "And it might give you a sense that this model is not realistic."
   ]
  },
  {
   "cell_type": "markdown",
   "id": "continuing-democrat",
   "metadata": {},
   "source": [
    "## Summary\n",
    "\n",
    "This chapter introduces a modeling framework that consists of three steps:\n",
    "\n",
    "* Abstraction is the process of defining a model by deciding which elements of the real world to include and which can be left out.\n",
    "\n",
    "* Analysis and simulation are ways to use a model to generate predictions, explain why things behave as they do, and design things that behave as we want.\n",
    "\n",
    "* Validation is how we test whether the model is right, often by comparing predictions with measurements from the real world.\n",
    "\n",
    "As a first example, we modeled a penny dropped from the Empire State building, including gravity but ignoring air resistance.\n",
    "In the exercises, you'll have a chance to try a better model, including air resistance.\n",
    "\n",
    "This chapter also presents Pint, a library for doing computation with units, which is convenient for converting between different units and helpful for avoiding catastrophic errors."
   ]
  },
  {
   "cell_type": "markdown",
   "id": "thousand-equation",
   "metadata": {},
   "source": [
    "## Exercises\n",
    "\n",
    "Before you go on, you might want to work on the following exercises."
   ]
  },
  {
   "cell_type": "markdown",
   "id": "periodic-objective",
   "metadata": {},
   "source": [
    "### Exercise 1\n",
    "\n",
    "In mathematical notation, we can write an equation like $v = a t$ and it's understood that we are multiplying $a$ and $t$.\n",
    "But that doesn't work in Python.  If you put two variables side-by-side, like this:\n",
    "\n",
    "```\n",
    "v = a t\n",
    "```\n",
    "\n",
    "you'll get a *syntax error*, which means that something is wrong with the structure of the program. Try it out so you see what the error message looks like."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 29,
   "id": "exempt-delight",
   "metadata": {
    "tags": []
   },
   "outputs": [],
   "source": [
    "a = 9.8 * meter / second**2\n",
    "t = 3.4 * second\n",
    "\n",
    "v = a * t\n",
    "v"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "pressing-sugar",
   "metadata": {},
   "source": [
    "### Exercise 2\n",
    "\n",
    "In this chapter we used the `sqrt` function from the NumPy library.  NumPy also provides a variable named `pi` that contains an approximation of the mathematical constant $\\pi$.\n",
    "We can import it like this:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 30,
   "id": "legal-observer",
   "metadata": {},
   "outputs": [],
   "source": [
    "from numpy import pi\n",
    "pi"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "aggregate-mambo",
   "metadata": {},
   "source": [
    "NumPy provides other functions we'll use, including `log`, `exp`, `sin`, and `cos`.\n",
    "Import `sin` and `cos` from NumPy and compute\n",
    "\n",
    "$$sin^2 (\\pi/4) + cos^2 (\\pi/4)$$\n",
    "\n",
    "Note: A mathematical identity tells us that the answer should be $1$."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 31,
   "id": "pressing-belgium",
   "metadata": {},
   "outputs": [],
   "source": [
    "# Solution goes here"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "unlimited-delivery",
   "metadata": {},
   "source": [
    "### Exercise 3\n",
    "\n",
    "Suppose you bring a 10 foot pole to the top of the Empire State Building and use it to drop the penny from `h` plus 10 feet.\n",
    "\n",
    "Define a variable named `foot` that contains the unit `foot` provided by the `UnitRegistry` we called `units`.  Define a variable named `pole_height` and give it the value 10 feet.\n",
    "\n",
    "What happens if you add `h`, which is in units of meters, to `pole_height`, which is in units of feet?  What happens if you write the addition the other way around?"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 32,
   "id": "inner-equivalent",
   "metadata": {},
   "outputs": [],
   "source": [
    "h = 381 * meter"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 33,
   "id": "nuclear-thirty",
   "metadata": {},
   "outputs": [],
   "source": [
    "# Solution goes here"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 34,
   "id": "available-steering",
   "metadata": {},
   "outputs": [],
   "source": [
    "# Solution goes here"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "aggressive-climate",
   "metadata": {},
   "source": [
    "### Exercise 4\n",
    "\n",
    "Why would it be nonsensical to add `a` and `t`? What happens if you try?"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 35,
   "id": "documentary-doctrine",
   "metadata": {},
   "outputs": [],
   "source": [
    "a = 9.8 * meter / second**2\n",
    "t = 3.4 * second"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "primary-partner",
   "metadata": {},
   "outputs": [],
   "source": []
  },
  {
   "cell_type": "markdown",
   "id": "legal-audio",
   "metadata": {},
   "source": [
    "In this example, you should get a `DimensionalityError`, which indicates that you have violated a rule of dimensional analysis: you cannot add quantities with different dimensions.\n",
    "\n",
    "The error messages you get from Python are big and scary, but if you read them carefully, they contain a lot of useful information.\n",
    "\n",
    "The last line usually tells you what type of error happened, and sometimes additional information, so you might want to start from the bottom and read up.\n",
    "\n",
    "The previous lines are a *traceback* of what was happening when the error occurred.  The first section of the traceback shows the code you wrote.  The following sections are often from Python libraries."
   ]
  },
  {
   "cell_type": "markdown",
   "id": "steady-chancellor",
   "metadata": {
    "tags": []
   },
   "source": [
    "Before you go on, you might want to delete the erroneous code so the notebook can run without errors."
   ]
  },
  {
   "cell_type": "markdown",
   "id": "valid-empire",
   "metadata": {},
   "source": [
    "### Exercise 5\n",
    "\n",
    "Suppose instead of dropping the penny, you throw it downward at its terminal velocity, $29$ m/s.  How long would it take to fall $381$ m?"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 36,
   "id": "greenhouse-reason",
   "metadata": {},
   "outputs": [],
   "source": [
    "# Solution goes here"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "asian-murray",
   "metadata": {},
   "source": [
    "### Exercise 6:\n",
    "\n",
    "So far we have considered two models of a falling penny:\n",
    "\n",
    "* If we ignore air resistance, the penny falls with constant acceleration, and we can compute the time to reach the sidewalk and the velocity of the penny when it gets there.\n",
    "\n",
    "* If we take air resistance into account, and drop the penny at its terminal velocity, it falls with constant velocity. \n",
    "\n",
    "Now let's consider a third model that includes elements of the first two: let's assume that the acceleration of the penny is `a` until the penny reaches $29$ m/s, and then $0$ m/s$^2$ afterwards.  What is the total time for the penny to fall $381$ m?"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "detailed-minnesota",
   "metadata": {},
   "source": [
    "You can break this question into three parts:\n",
    "\n",
    "1. How long would the penny take to reach $29$ m/s with constant acceleration `a`.\n",
    "2. How far would it fall during that time?\n",
    "3. How long would it take to fall the remaining distance with constant velocity $29$ m/s?\n",
    "\n",
    "Suggestion: Assign each intermediate result to a variable with a meaningful name.  And assign units to all quantities!"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 37,
   "id": "secure-crowd",
   "metadata": {},
   "outputs": [],
   "source": [
    "a = 9.8 * meter / second**2\n",
    "h = 381 * meter"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 38,
   "id": "thirty-minneapolis",
   "metadata": {},
   "outputs": [],
   "source": [
    "# Solution goes here"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 39,
   "id": "premier-seeking",
   "metadata": {},
   "outputs": [],
   "source": [
    "# Solution goes here"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 40,
   "id": "brave-laundry",
   "metadata": {},
   "outputs": [],
   "source": [
    "# Solution goes here"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 41,
   "id": "adjusted-consultation",
   "metadata": {},
   "outputs": [],
   "source": [
    "# Solution goes here"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 42,
   "id": "understanding-consortium",
   "metadata": {},
   "outputs": [],
   "source": [
    "# Solution goes here"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "composed-tunnel",
   "metadata": {},
   "source": [
    "### Exercise 7\n",
    "\n",
    "When I was in high school, the pitcher on the baseball team claimed that when he threw a fastball he was throwing the ball down; that is, the ball left his hand at a downward angle.\n",
    "I was skeptical; watching from the side, I thought the ball left his hand at an upward angle.\n",
    "\n",
    "Can you think of a simple model you could use to settle the argument?  What factors would you include and what could you ignore?  What quantities would you have to look up or estimate?\n",
    "\n",
    "I suggest you convert all quantities to SI units like meters and seconds (see <https://en.wikipedia.org/wiki/International_System_of_Units>)."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 43,
   "id": "about-complex",
   "metadata": {},
   "outputs": [],
   "source": [
    "# Solution goes here"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 44,
   "id": "unique-owner",
   "metadata": {},
   "outputs": [],
   "source": [
    "# Solution goes here"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 45,
   "id": "minus-batman",
   "metadata": {},
   "outputs": [],
   "source": [
    "# Solution goes here"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 46,
   "id": "exact-vegetable",
   "metadata": {},
   "outputs": [],
   "source": [
    "# Solution goes here"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 47,
   "id": "neutral-lightning",
   "metadata": {},
   "outputs": [],
   "source": [
    "# Solution goes here"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "jewish-secret",
   "metadata": {},
   "source": [
    "### Exercise 8\n",
    "\n",
    "Suppose I run a 10K race in 44:52 (44 minutes and 52 seconds).  What is my average pace in minutes per mile?"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 48,
   "id": "virgin-cambodia",
   "metadata": {},
   "outputs": [],
   "source": [
    "mile = units.mile\n",
    "kilometer = units.kilometer\n",
    "minute = units.minute"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 49,
   "id": "right-intention",
   "metadata": {},
   "outputs": [],
   "source": [
    "# Solution goes here"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 50,
   "id": "mineral-sally",
   "metadata": {},
   "outputs": [],
   "source": [
    "# Solution goes here"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 51,
   "id": "coral-camel",
   "metadata": {},
   "outputs": [],
   "source": [
    "# Solution goes here"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 52,
   "id": "preceding-cricket",
   "metadata": {},
   "outputs": [],
   "source": [
    "# Solution goes here"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 53,
   "id": "effective-rendering",
   "metadata": {},
   "outputs": [],
   "source": [
    "# Solution goes here"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 54,
   "id": "printable-reply",
   "metadata": {},
   "outputs": [],
   "source": [
    "# Solution goes here"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "environmental-wallet",
   "metadata": {
    "tags": []
   },
   "source": [
    "## More Jupyter\n",
    "\n",
    "You can add and remove cells from a notebook using the buttons in the toolbar and the items in the menu, both of which you should see at the top of this notebook.\n",
    "\n",
    "Try the following exercises:\n",
    "\n",
    "1.  From the Insert menu select \"Insert cell below\" to add a cell below this one.  By default, you get a code cell, as you can see in the pulldown menu that says \"Code\".\n",
    "\n",
    "2.  In the new cell, add a print statement like `print('Hello')`, and run it.\n",
    "\n",
    "3.  Add another cell, select the new cell, and then click on the pulldown menu that says \"Code\" and select \"Markdown\".  This makes the new cell a text cell.\n",
    "\n",
    "4.  In the new cell, type some text, and then run it.\n",
    "\n",
    "5.  Use the arrow buttons in the toolbar to move cells up and down.\n",
    "\n",
    "6.  Use the cut, copy, and paste buttons to delete, add, and move cells.\n",
    "\n",
    "7.  As you make changes, Jupyter saves your notebook automatically, but if you want to make sure, you can press the save button, which looks like a floppy disk from the 1990s.\n",
    "\n",
    "8.  Finally, when you are done with a notebook, select \"Close and Halt\" from the File menu."
   ]
  },
  {
   "cell_type": "markdown",
   "id": "successful-kentucky",
   "metadata": {
    "tags": []
   },
   "source": [
    "When you change the contents of a cell, you have to run it again for those changes to have an effect.  If you forget to do that, the results can be confusing, because the code you are looking at is not the code you ran.\n",
    "\n",
    "If you ever lose track of which cells have run, and in what order, you should go to the Kernel menu and select \"Restart & Run All\".  Restarting the kernel means that all of your variables get deleted, and running all the cells means all of your code will run again, in the right order.\n",
    "\n",
    "Select \"Restart & Run All\" now and confirm that it runs all of the cells."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "weighted-quebec",
   "metadata": {},
   "outputs": [],
   "source": []
  }
 ],
 "metadata": {
  "celltoolbar": "Tags",
  "kernelspec": {
   "display_name": "Python 3 (ipykernel)",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.10.13"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 5
}
